package org.idea.spring.bean.aware;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

/**
 * @Author linhao
 * @Date created in 2:06 下午 2021/5/2
 */
public class DisposablePersonBeanDemo implements DisposableBean {

    @Bean
    //默认是单例对象
    public static Person singletonPerson() {
        return createPerson();
    }

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public static Person prototypePerson() {
        return createPerson();
    }

    @Autowired
    @Qualifier("singletonPerson")
    private Person singletonPerson;

    @Autowired
    @Qualifier("prototypePerson")
    private Person prototypePerson;

    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
        annotationConfigApplicationContext.register(DisposablePersonBeanDemo.class);
        annotationConfigApplicationContext.refresh();
        System.out.println("开始依赖查找");
        lookUpBean(annotationConfigApplicationContext);
        annotationConfigApplicationContext.close();
    }

    /**
     * Singleton Bean 只会初始化一次，而 Prototype Bean 每次都会初始化，不过仅 Singleton Bean 会执行销毁方法回调。
     * @param annotationConfigApplicationContext
     */
    public static void lookUpBean(AnnotationConfigApplicationContext annotationConfigApplicationContext) {
        Person singletonPerson = annotationConfigApplicationContext.getBean("singletonPerson", Person.class);
        System.out.println(singletonPerson.toString());
        Person prototypePerson = annotationConfigApplicationContext.getBean("prototypePerson", Person.class);
        System.out.println(prototypePerson.toString());
    }

    public static Person createPerson() {
        Person person = new Person();
        return person;
    }

    /**
     * 基于DisposableBean 的销毁才触发销毁状态，如果bean的销毁和当前对象不在同一个周期阶段销毁，那么可以尝试
     * 使用addBeanFactoryPostProcessor监听器的方式进行bean的销毁
     * @throws Exception
     */
    @Override
    public void destroy() throws Exception {
        this.singletonPerson.destroy();
        this.prototypePerson.destroy();
    }
}
